<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="世代名称" prop="geneName">
              <el-input v-model="queryParams.geneName" placeholder="请输入世代名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="谱名" prop="name">
              <el-input v-model="queryParams.name" placeholder="请输入谱名" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="姓氏" prop="lastName">
              <el-input v-model="queryParams.lastName" placeholder="请输入姓氏" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="常用名" prop="commonName">
              <el-input v-model="queryParams.commonName" placeholder="请输入常用名" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="别名" prop="alias">
              <el-input v-model="queryParams.alias" placeholder="请输入别名" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="说明" prop="desc">
              <el-input v-model="queryParams.desc" placeholder="请输入说明" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="父节点" prop="parentId">
              <el-input v-model="queryParams.parentId" placeholder="请输入父节点" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="关系(生、抚子等)" prop="relation">
              <el-select v-model="queryParams.relation" placeholder="请选择关系(生、抚子等)" clearable>
                <el-option v-for="dict in relation" :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
            <el-form-item label="父母名称" prop="parentName">
              <el-input v-model="queryParams.parentName" placeholder="请输入父母名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="排行" prop="rank">
              <el-select v-model="queryParams.rank" placeholder="请选择排行" clearable>
                <el-option v-for="dict in rank" :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
            <el-form-item label="学校" prop="school">
              <el-input v-model="queryParams.school" placeholder="请输入学校" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="专业" prop="professional">
              <el-input v-model="queryParams.professional" placeholder="请输入专业" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="学历" prop="degree">
              <el-select v-model="queryParams.degree" placeholder="请选择学历" clearable>
                <el-option v-for="dict in degree" :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
            <el-form-item label="性别" prop="gender">
              <el-input v-model="queryParams.gender" placeholder="请输入性别" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="职务" prop="duties">
              <el-input v-model="queryParams.duties" placeholder="请输入职务" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="头衔" prop="title">
              <el-input v-model="queryParams.title" placeholder="请输入头衔" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="出生日期" prop="birthday">
              <el-input v-model="queryParams.birthday" placeholder="请输入出生日期" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="死亡时间" prop="deadTime">
              <el-input v-model="queryParams.deadTime" placeholder="请输入死亡时间" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="葬地" prop="burialSite">
              <el-input v-model="queryParams.burialSite" placeholder="请输入葬地" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="配偶主键id" prop="otherId">
              <el-input v-model="queryParams.otherId" placeholder="请输入配偶主键id" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="族谱id" prop="geId">
              <el-input v-model="queryParams.geId" placeholder="请输入族谱id" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd()" v-hasPermi="['genealogy:name:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" plain icon="Sort" @click="handleToggleExpandAll">展开/折叠</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>
      <el-table
        ref="nameTableRef"
        v-loading="loading"
        :data="nameList"
        row-key="id"
        border
        :default-expand-all="isExpandAll"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column label="世代名称" prop="geneName" />
        <el-table-column label="谱名" align="center" prop="name" />
        <el-table-column label="姓氏" align="center" prop="lastName" />
        <el-table-column label="常用名" align="center" prop="commonName" />
        <el-table-column label="别名" align="center" prop="alias" />
        <el-table-column label="说明" align="center" prop="desc" />
        <el-table-column label="父节点" align="center" prop="parentId" />
        <el-table-column label="关系(生、抚子等)" align="center" prop="relation">
          <template #default="scope">
            <dict-tag :options="relation" :value="scope.row.relation"/>
          </template>
        </el-table-column>
        <el-table-column label="父母名称" align="center" prop="parentName" />
        <el-table-column label="排行" align="center" prop="rank">
          <template #default="scope">
            <dict-tag :options="rank" :value="scope.row.rank"/>
          </template>
        </el-table-column>
        <el-table-column label="学校" align="center" prop="school" />
        <el-table-column label="专业" align="center" prop="professional" />
        <el-table-column label="学历" align="center" prop="degree">
          <template #default="scope">
            <dict-tag :options="degree" :value="scope.row.degree"/>
          </template>
        </el-table-column>
        <el-table-column label="性别" align="center" prop="gender" />
        <el-table-column label="职务" align="center" prop="duties" />
        <el-table-column label="头衔" align="center" prop="title" />
        <el-table-column label="出生日期" align="center" prop="birthday" />
        <el-table-column label="状态(去世/在世)" align="center" prop="status" />
        <el-table-column label="死亡时间" align="center" prop="deadTime" />
        <el-table-column label="葬地" align="center" prop="burialSite" />
        <el-table-column label="配偶关系" align="center" prop="personType" />
        <el-table-column label="配偶主键id" align="center" prop="otherId" />
        <el-table-column label="族谱id" align="center" prop="geId" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['genealogy:name:edit']" />
            </el-tooltip>
            <el-tooltip content="新增" placement="top">
              <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)" v-hasPermi="['genealogy:name:add']" />
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['genealogy:name:remove']" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加或修改世代名称对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="nameFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="世代名称" prop="geneName">
          <el-input v-model="form.geneName" placeholder="请输入世代名称" />
        </el-form-item>
        <el-form-item label="谱名" prop="name">
          <el-input v-model="form.name" placeholder="请输入谱名" />
        </el-form-item>
        <el-form-item label="姓氏" prop="lastName">
          <el-input v-model="form.lastName" placeholder="请输入姓氏" />
        </el-form-item>
        <el-form-item label="常用名" prop="commonName">
          <el-input v-model="form.commonName" placeholder="请输入常用名" />
        </el-form-item>
        <el-form-item label="别名" prop="alias">
          <el-input v-model="form.alias" placeholder="请输入别名" />
        </el-form-item>
        <el-form-item label="说明" prop="desc">
          <el-input v-model="form.desc" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="父节点" prop="parentId">
          <el-tree-select
            v-model="form.parentId"
            :data="nameOptions"
            :props="{ value: 'id', label: 'name', children: 'children' }"
            value-key="id"
            placeholder="请选择父节点"
            check-strictly
          />
        </el-form-item>
        <el-form-item label="关系(生、抚子等)" prop="relation">
          <el-select v-model="form.relation" placeholder="请选择关系(生、抚子等)">
            <el-option
              v-for="dict in relation"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="父母名称" prop="parentName">
          <el-input v-model="form.parentName" placeholder="请输入父母名称" />
        </el-form-item>
        <el-form-item label="排行" prop="rank">
          <el-select v-model="form.rank" placeholder="请选择排行">
            <el-option
              v-for="dict in rank"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学校" prop="school">
          <el-input v-model="form.school" placeholder="请输入学校" />
        </el-form-item>
        <el-form-item label="专业" prop="professional">
          <el-input v-model="form.professional" placeholder="请输入专业" />
        </el-form-item>
        <el-form-item label="学历" prop="degree">
          <el-select v-model="form.degree" placeholder="请选择学历">
            <el-option
              v-for="dict in degree"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-input v-model="form.gender" placeholder="请输入性别" />
        </el-form-item>
        <el-form-item label="职务" prop="duties">
          <el-input v-model="form.duties" placeholder="请输入职务" />
        </el-form-item>
        <el-form-item label="头衔" prop="title">
          <el-input v-model="form.title" placeholder="请输入头衔" />
        </el-form-item>
        <el-form-item label="出生日期" prop="birthday">
          <el-input v-model="form.birthday" placeholder="请输入出生日期" />
        </el-form-item>
        <el-form-item label="死亡时间" prop="deadTime">
          <el-input v-model="form.deadTime" placeholder="请输入死亡时间" />
        </el-form-item>
        <el-form-item label="葬地" prop="burialSite">
          <el-input v-model="form.burialSite" placeholder="请输入葬地" />
        </el-form-item>
        <el-form-item label="配偶主键id" prop="otherId">
          <el-input v-model="form.otherId" placeholder="请输入配偶主键id" />
        </el-form-item>
        <el-form-item label="族谱id" prop="geId">
          <el-input v-model="form.geId" placeholder="请输入族谱id" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Name" lang="ts">
import { listName, getName, delName, addName, updateName } from "@/api/genealogy/name";
import { NameVO, NameQuery, NameForm } from '@/api/genealogy/name/types';

type NameOption = {
  id: number;
  name: string;
  children?: NameOption[];
}

const { proxy } = getCurrentInstance() as ComponentInternalInstance;;

const { degree, rank, relation } = toRefs<any>(proxy?.useDict('degree', 'rank', 'relation'));

const nameList = ref<NameVO[]>([]);
const nameOptions = ref<NameOption[]>([]);
const buttonLoading = ref(false);
const showSearch = ref(true);
const isExpandAll = ref(true);
const loading = ref(false);

const queryFormRef = ref<ElFormInstance>();
const nameFormRef = ref<ElFormInstance>();
const nameTableRef = ref<ElTableInstance>()

const dialog = reactive<DialogOption>({
    visible: false,
    title: ''
});


const initFormData: NameForm = {
    id: undefined,
    geneName: undefined,
    name: undefined,
    lastName: undefined,
    commonName: undefined,
    alias: undefined,
    mark: undefined,
    parentId: undefined,
    relation: undefined,
    parentName: undefined,
    rankNo: undefined,
    school: undefined,
    professional: undefined,
    degree: undefined,
    gender: undefined,
    duties: undefined,
    title: undefined,
    birthday: undefined,
    status: undefined,
    deadTime: undefined,
    burialSite: undefined,
    personType: undefined,
    otherId: undefined,
    geId: undefined,
}

const data = reactive<PageData<NameForm, NameQuery>>({
  form: {...initFormData},
  queryParams: {
    geneName: undefined,
    name: undefined,
    lastName: undefined,
    commonName: undefined,
    alias: undefined,
    mark: undefined,
    parentId: undefined,
    relation: undefined,
    parentName: undefined,
    rankNo: undefined,
    school: undefined,
    professional: undefined,
    degree: undefined,
    gender: undefined,
    duties: undefined,
    title: undefined,
    birthday: undefined,
    status: undefined,
    deadTime: undefined,
    burialSite: undefined,
    personType: undefined,
    otherId: undefined,
    geId: undefined,
    params: {
    }
  },
  rules: {
    lastName: [
      { required: true, message: "姓氏不能为空", trigger: "blur" }
    ],
    commonName: [
      { required: true, message: "常用名不能为空", trigger: "blur" }
    ],
    alias: [
      { required: true, message: "别名不能为空", trigger: "blur" }
    ],
    desc: [
      { required: true, message: "说明不能为空", trigger: "blur" }
    ],
    relation: [
      { required: true, message: "关系(生、抚子等)不能为空", trigger: "change" }
    ],
    parentName: [
      { required: true, message: "父母名称不能为空", trigger: "blur" }
    ],
    rank: [
      { required: true, message: "排行不能为空", trigger: "change" }
    ],
    school: [
      { required: true, message: "学校不能为空", trigger: "blur" }
    ],
    professional: [
      { required: true, message: "专业不能为空", trigger: "blur" }
    ],
    degree: [
      { required: true, message: "学历不能为空", trigger: "change" }
    ],
    gender: [
      { required: true, message: "性别不能为空", trigger: "blur" }
    ],
    duties: [
      { required: true, message: "职务不能为空", trigger: "blur" }
    ],
    title: [
      { required: true, message: "头衔不能为空", trigger: "blur" }
    ],
    birthday: [
      { required: true, message: "出生日期不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "状态(去世/在世)不能为空", trigger: "change" }
    ],
    deadTime: [
      { required: true, message: "死亡时间不能为空", trigger: "blur" }
    ],
    burialSite: [
      { required: true, message: "葬地不能为空", trigger: "blur" }
    ],
    personType: [
      { required: true, message: "配偶关系不能为空", trigger: "change" }
    ],
    otherId: [
      { required: true, message: "配偶主键id不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询世代名称列表 */
const getList = async () => {
  loading.value = true;
  const res = await listName(queryParams.value);
  const data = proxy?.handleTree<NameVO>(res.data, "id", "parentId");
  if (data) {
    nameList.value = data;
    loading.value = false;
  }
}

/** 查询世代名称下拉树结构 */
const getTreeselect = async () => {
  const res = await listName();
  nameOptions.value = [];
  const data: NameOption = { id: 0, name: '顶级节点', children: [] };
  data.children = proxy?.handleTree<NameOption>(res.data, "id", "parentId");
  nameOptions.value.push(data);
}

// 取消按钮
const cancel = () => {
  reset();
  dialog.visible = false;
}

// 表单重置
const reset = () => {
  form.value = {...initFormData}
  nameFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 新增按钮操作 */
const handleAdd = (row?: NameVO) => {
  reset();
  getTreeselect();
  if (row != null && row.id) {
    form.value.parentId = row.id;
  } else {
    form.value.parentId = 0;
  }
  dialog.visible = true;
  dialog.title = "添加世代名称";
}

/** 展开/折叠操作 */
const handleToggleExpandAll = () => {
  isExpandAll.value = !isExpandAll.value;
  toggleExpandAll(nameList.value, isExpandAll.value)
}

/** 展开/折叠操作 */
const toggleExpandAll = (data: NameVO[], status: boolean) => {
  data.forEach((item) => {
    nameTableRef.value?.toggleRowExpansion(item, status)
    if (item.children && item.children.length > 0) toggleExpandAll(item.children, status)
  })
}

/** 修改按钮操作 */
const handleUpdate = async (row: NameVO) => {
  reset();
  await getTreeselect();
  if (row != null) {
    form.value.parentId = row.parentId;
  }
  const res = await getName(row.id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改世代名称";
}

/** 提交按钮 */
const submitForm = () => {
  nameFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateName(form.value).finally(() => buttonLoading.value = false);
      } else {
        await addName(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row: NameVO) => {
  await proxy?.$modal.confirm('是否确认删除世代名称编号为"' + row.id + '"的数据项？');
  loading.value = true;
  await delName(row.id).finally(() => loading.value = false);
  await getList();
  proxy?.$modal.msgSuccess("删除成功");
}

onMounted(() => {
  getList();
});
</script>
